package com.ydd.moudle.me;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.taofengsdk.okhttp.listener.DisposeDataListener;
import com.ydd.R;
import com.ydd.base.BaseActivity;
import com.ydd.jpush.PushMessage;
import com.ydd.jpush.PushMessageActivity;
import com.ydd.model.event.LoginEvent;
import com.ydd.model.user.User;
import com.ydd.model.user.UserInfo;
import com.ydd.network.http.RequestCenter;
import com.ydd.network.mina.MinaService;
import com.ydd.network.mina.SessionManager;
import com.ydd.share.ShareManager;
import com.ydd.util.DialogManager;
import com.ydd.util.db.SPManager;
import com.ydd.util.user.UserManager;
import com.ydd.widegt.associatemail.MailBoxAssociateView;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * Created by tao on 17-3-17.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    /**
     * UI
     */
    private MailBoxAssociateView mUserNameView;
    private EditText mPasswordView;
    private TextView mLoginView;
    private TextView mQQLoginView;
    private TextView mWeixinLoginView;
    private TextView mSinaWebLoginView;
    private CheckBox mRememberPassword;
    private CheckBox mAutoLogin;

    private PushMessage pushMessage;
    private boolean fromPush;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);

        initData();
        initView();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent.hasExtra("pushMessage")) {
            pushMessage = (PushMessage) intent.getSerializableExtra("pushMessage");
        }
        fromPush = intent.getBooleanExtra("fromPush", false);
    }

    private void initView() {
        mUserNameView = (MailBoxAssociateView) findViewById(R.id.associate_email_input);
        mPasswordView = (EditText) findViewById(R.id.login_input_password);
        mLoginView = (TextView) findViewById(R.id.login_button);
        mQQLoginView = (TextView) findViewById(R.id.qq_login_view);
        mWeixinLoginView = (TextView) findViewById(R.id.weixin_login_view);
        mSinaWebLoginView = (TextView) findViewById(R.id.sinaweb_login_view);
        mRememberPassword = (CheckBox) findViewById(R.id.remember_password);
        mAutoLogin = (CheckBox) findViewById(R.id.auto_login);

        mLoginView.setOnClickListener(this);
        mQQLoginView.setOnClickListener(this);
        mWeixinLoginView.setOnClickListener(this);
        mSinaWebLoginView.setOnClickListener(this);

        showLoginStatus(mUserNameView, mPasswordView, mRememberPassword, mAutoLogin);
    }

    private void showLoginStatus(MailBoxAssociateView mUserNameView, EditText mPasswordView,
                                 CheckBox mRememberPassword, CheckBox mAutoLogin) {
        String userName = SPManager.getInstance().getString(SPManager.USER_NAME, "");
        String userPassword = SPManager.getInstance().getString(SPManager.USER_PASSWORD, "");
        boolean rememberPassword = SPManager.getInstance().getBoolean(SPManager.REMEMBER_PASSWORD_USER
                , false);
        boolean autoLogin = SPManager.getInstance().getBoolean(SPManager.AUTOMATIC__LOGIN_USER, false);
        if (rememberPassword && autoLogin) {
            mUserNameView.setText(userName);
            mPasswordView.setText(userPassword);
            mRememberPassword.isChecked();
            mAutoLogin.setChecked(true);
        } else if (rememberPassword) {
            mUserNameView.setText(userName);
            mPasswordView.setText(userPassword);
            mRememberPassword.setChecked(true);
        } else if (autoLogin) {
            mAutoLogin.setChecked(true);
        } else {

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_button:
                login();
                break;
            case R.id.qq_login_view:
                threeLogin(ShareManager.PlatformType.QQ);
                break;
            case R.id.weixin_login_view:
                threeLogin(ShareManager.PlatformType.WeChat);
                break;
            case R.id.sinaweb_login_view:
                threeLogin(ShareManager.PlatformType.SinaWeibo);
                break;
            default:
                break;
        }
    }

    private void threeLogin(ShareManager.PlatformType type) {
        DialogManager.getInstnce().showProgressDialog(this);
        ShareManager.getInstance().getUserMsg(type, new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                DialogManager.getInstnce().dismissProgressDialog();

                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(platform.getDb().getUserId());
                userInfo.setName(platform.getDb().getUserName());
                userInfo.setPhotoUrl(platform.getDb().getUserIcon());
                userInfo.setPlatform(platform.getDb().getPlatformNname());
                User user = new User();
                user.setData(userInfo);
                //保存用户信息并通知其他模块登陆成功
                UserManager.getInstance().setUser(user);
                connectToSever();

                saveUserInfo(userInfo.getName(), userInfo.getPassword(), userInfo.getPhotoUrl(),
                        false, false);
                EventBus.getDefault().post(new LoginEvent());

                finish();
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                DialogManager.getInstnce().dismissProgressDialog();
                Log.e(TAG, "onError: " + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                DialogManager.getInstnce().dismissProgressDialog();
                Log.e(TAG, "onCancel: " + i);
            }
        });
    }

    private void login() {
        final String userName = mUserNameView.getText().toString().trim();//trim 移除字符串两侧空白符号
        final String password = mPasswordView.getText().toString().trim();
        DialogManager.getInstnce().showProgressDialog(this);

        RequestCenter.requestUserLogin(userName, password, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                DialogManager.getInstnce().dismissProgressDialog();

                User user = (User) responseObj;
                UserManager.getInstance().setUser(user);
                if (userName.equals(user.getData().getName()) && password.equals(user.getData().getPassword())) {
                    Toast.makeText(LoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();

                    if (mRememberPassword.isChecked() && mAutoLogin.isChecked()) {
                        saveUserInfo(userName, password, "", true, true);
                    }
                    if (mRememberPassword.isChecked() && !mAutoLogin.isChecked()) {
                        saveUserInfo(userName, password, "", true, false);
                    }
                    if (mAutoLogin.isChecked() && !mRememberPassword.isChecked()) {
                        saveUserInfo(userName, password, "", false, true);
                    }
                    if (!mAutoLogin.isChecked() && !mRememberPassword.isChecked()) {
                        saveUserInfo(userName, password, "", false, false);
                    }
                    connectToSever();
                    EventBus.getDefault().post(new LoginEvent());
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "用戶名或密码错误", Toast.LENGTH_SHORT).show();
                }


                if (fromPush) {
                    Intent intent = new Intent(LoginActivity.this, PushMessageActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("pushMessage", pushMessage);
                    startActivity(intent);
                }

            }

            @Override
            public void onFailure(Object reasonObj) {
                DialogManager.getInstnce().dismissProgressDialog();
                Toast.makeText(LoginActivity.this, "网络连接错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveUserInfo(String userName, String password, String photoUrl, boolean rememberPassword, boolean autoLogin) {
        SPManager.getInstance().putString(SPManager.USER_NAME, userName);
        SPManager.getInstance().putString(SPManager.USER_PASSWORD, password);
        SPManager.getInstance().putString(SPManager.USER_PHOTO_URL, photoUrl);
        SPManager.getInstance().putBoolean(SPManager.REMEMBER_PASSWORD_USER, rememberPassword);
        SPManager.getInstance().putBoolean(SPManager.AUTOMATIC__LOGIN_USER, autoLogin);
        SPManager.getInstance().putBoolean(SPManager.IS_LOGIN_USER, true);
    }

    //启动长连接
    private void connectToSever() {
        Intent intent = new Intent(LoginActivity.this, MinaService.class);
        startService(intent);
    }
}
